﻿
namespace EasyNet.Solr.Impl
{
    using System.Runtime.Serialization.Json;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;

    public class JsonResponseHeaderParser : ISolrResponseParser<string, ResponseHeader>
    {
        public ResponseHeader Parse(string result)
        {
            if (string.IsNullOrEmpty(result))
            {
                return null;
            }

            var bytes = Encoding.UTF8.GetBytes(result);

            using (var reader = JsonReaderWriterFactory.CreateJsonReader(bytes, XmlDictionaryReaderQuotas.Max))
            {
                var xmlDoc = XDocument.Load(reader);

                var responseHeader = xmlDoc.Root.Element("responseHeader");

                if (responseHeader == null)
                {
                    return null;
                }

                return new ResponseHeader()
                {
                    Status = int.Parse(responseHeader.Element("status").Value),
                    QTime = int.Parse(responseHeader.Element("QTime").Value)
                };
            }
        }
    }
}
